using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Prism.Commands;
using Prism.Mvvm;
using SanmaoTools.Models;
using SanmaoTools.Common.Untils;

namespace Tryit.ViewModels
{
    public class PhysicalPropertiesEditDialogViewModel : BindableBase
    {
        private PhysicalProperties _physicalProperty;
        public PhysicalProperties PhysicalProperty
        {
            get => _physicalProperty;
            set => SetProperty(ref _physicalProperty, value);
        }

        private ObservableCollection<string> _brandList;
        public ObservableCollection<string> BrandList
        {
            get => _brandList;
            set => SetProperty(ref _brandList, value);
        }

        private string _brandInput;
        public string BrandInput
        {
            get => _brandInput;
            set
            {
                if (SetProperty(ref _brandInput, value))
                {
                    FilterBrandList();
                    if (BrandList.Contains(_brandInput))
                        PhysicalProperty.Brand = _brandInput;
                }
            }
        }

        private ObservableCollection<string> _filteredBrandList = new ObservableCollection<string>();
        public ObservableCollection<string> FilteredBrandList
        {
            get => _filteredBrandList;
            set => SetProperty(ref _filteredBrandList, value);
        }

        public DelegateCommand OkCommand { get; }
        public DelegateCommand CancelCommand { get; }

        private readonly Window _dialog;

        public PhysicalPropertiesEditDialogViewModel(PhysicalProperties physicalProperty, Window dialog)
        {
            _dialog = dialog;
            BrandList = new ObservableCollection<string>();
            PhysicalProperty = physicalProperty ?? new PhysicalProperties
            {
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            };

            OkCommand = new DelegateCommand(ExecuteOk);
            CancelCommand = new DelegateCommand(ExecuteCancel);

            // 在构造函数最后加载品牌列表
            LoadBrandList();
        }

        private void LoadBrandList()
        {
            try
            {
                using (var db = new SqlSugarHelper().GetInstance())
                {
                    var brands = db.Queryable<BrandAndStoveNumber>()
                        .Select(it => it.Name)
                        .Distinct()
                        .ToList();

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        BrandList.Clear();
                        foreach (var brand in brands)
                        {
                            if (!string.IsNullOrWhiteSpace(brand))
                            {
                                BrandList.Add(brand);
                            }
                        }
                        // 初始化
                        BrandInput = PhysicalProperty.Brand;
                        FilterBrandList();
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载牌号列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void FilterBrandList()
        {
            if (string.IsNullOrWhiteSpace(BrandInput))
            {
                FilteredBrandList = new ObservableCollection<string>(BrandList);
            }
            else
            {
                var filtered = BrandList.Where(b => b != null && b.Contains(BrandInput, StringComparison.OrdinalIgnoreCase)).ToList();
                FilteredBrandList = new ObservableCollection<string>(filtered);
            }
        }

        private void ExecuteOk()
        {
            if (string.IsNullOrWhiteSpace(PhysicalProperty.Brand))
            {
                MessageBox.Show("请选择牌号", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (!PhysicalProperty.Date.HasValue)
            {
                MessageBox.Show("请选择日期", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 验证数值字段
            if (!string.IsNullOrEmpty(PhysicalProperty.TensileStrength) && !IsTextConvertibleToDouble(PhysicalProperty.TensileStrength))

            {
                MessageBox.Show("抗拉强度必须是有效的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (!string.IsNullOrEmpty(PhysicalProperty.YieldStrength) && !IsTextConvertibleToDouble(PhysicalProperty.YieldStrength))

            {
                MessageBox.Show("屈服强度必须是有效的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (!string.IsNullOrEmpty(PhysicalProperty.Elongation) && !IsTextConvertibleToDouble(PhysicalProperty.Elongation))
            {
                MessageBox.Show("延伸率必须是有效的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (!string.IsNullOrEmpty(PhysicalProperty.Hardness) && !IsTextConvertibleToDouble(PhysicalProperty.Hardness))
            {
                MessageBox.Show("硬度必须是有效的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (!string.IsNullOrEmpty(PhysicalProperty.HydrogenContent) && !IsTextConvertibleToDouble(PhysicalProperty.HydrogenContent))
            {
                MessageBox.Show("含氢量必须是有效的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            _dialog.DialogResult = true;
            _dialog.Close();
        }

        public bool IsTextConvertibleToDouble(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return false;
            }

            double result;
            return double.TryParse(text, out result);
        }

        private void ExecuteCancel()
        {
            _dialog.DialogResult = false;
            _dialog.Close();
        }
    }
}